<template>
  <div>
    <el-form :inline="true" :model="roleRef.rolePage">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="roleRef.rolePage.roleName" placeholder="角色名称" type="text" />
      </el-form-item>
      <el-form-item label="状态" prop="roleName">
        <el-select v-model="roleRef.rolePage.isWork" placeholder="状态">
          <el-option v-for="item in roleRef.types" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchRole">搜索</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div>
    <el-col :span="6">
      <el-button type="primary" @click="roleRef.dialogFormVisible = true">
        <el-icon>
          <Plus />
        </el-icon>
        添加角色
      </el-button>
    </el-col>
  </div>
  <div>
    <el-table :data="roleRef.roleTable" stripe style="width: 100%">
      <el-table-column align="center" label="序号" type="index" width="80">
        <template #default="scope">
          {{ (roleRef.rolePage.page - 1) * roleRef.rolePage.size + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column align="center" header-align="center" label="角色名称" prop="roleName" />
      <el-table-column align="center" header-align="center" label="排序" prop="roleSort" />
      <el-table-column align="center" header-align="center" label="角色状态">
        <template #default="scope">
          <el-switch
            v-model="scope.row.work"
            :active-value="true"
            :disabled="!scope.row.edit"
            :inactive-value="false"
            active-text="是"
            inactive-text="否"
            inline-prompt
            @change="chengStatus(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" header-align="center" label="创建时间" prop="createTime" />
      <el-table-column align="center" fixed="right" header-align="center" label="操作">
        <template #default="scope">
          <el-button :disabled="!scope.row.edit" link size="small" type="primary" @click="edit(scope.row)"> 编辑 </el-button>
          <el-button :disabled="!scope.row.edit" link size="small" type="primary" @click="addMenu(scope.row)">配置权限 </el-button>
          <el-popconfirm title="确定要删除吗?" @confirm="deleted(scope.row)">
            <template #reference>
              <el-button :disabled="!scope.row.edit" link type="primary">删除 </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <el-dialog v-model="roleRef.dialogFormVisible" title="添加角色" destroy-on-close @close="resetForm(addRoleRef)">
    <el-form ref="addRoleRef" :model="roleRef.roleAdd" :rules="roleRef.addRoleRuls">
      <el-form-item label="角色名称：" prop="roleName">
        <el-input v-model="roleRef.roleAdd.roleName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="角色编码：" prop="code">
        <el-input v-model="roleRef.roleAdd.code" autocomplete="off" />
      </el-form-item>
      <el-form-item label="排序：" prop="roleSort">
        <el-input-number v-model="roleRef.roleAdd.roleSort" :min="0" :step="1" />
      </el-form-item>
      <el-form-item label="备注：" prop="remark">
        <Editor v-model:editorValue="roleRef.roleAdd.remark"></Editor>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveRole(addRoleRef)">保存</el-button>
        <el-button @click="roleRef.dialogFormVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <el-dialog v-model="roleRef.dialogMenu" title="添加权限">
    <el-row :gutter="30">
      <el-col :span="24">
        <el-button type="primary" @click="isTreeChecked(roleRef.treeChecked)">全选/取消全选 </el-button>
      </el-col>
    </el-row>
    <el-row :gutter="30">
      <el-col :span="24">
        <el-tree ref="treeRef" :check-strictly="true" :data="menuTreeRef.treeData" :props="roleRef.props" node-key="id" show-checkbox @node-click="handleNodeClick" />
      </el-col>
    </el-row>
    <el-row :gutter="30">
      <el-col :span="24">
        <el-button type="primary" @click="saveTree()">保存</el-button>
        <el-button @click="roleRef.dialogMenu = false">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
  <div class="pagination-block">
    <Page :pageData="roleRef.rolePage" @selectPage="searchRole"></Page>
  </div>
</template>
<script lang="ts" setup>
import { roleClass, roleInfo } from '@/page/types/admin/role'
import { menuTreeClass, menuTreeInfo } from '@/page/types/admin/menuTree'
import { addRole, deleteRole, getRoleDetail, pageRole, saveRoleMenu, treeSelect, updateRole } from '@/api/admin'
import { ElMessage, ElTree, FormInstance } from 'element-plus/es'
import { baseTreeInfo } from '@/page/types/base/baseTree'
import { roleMenuClass } from '@/page/types/admin/roleMenu'
import Editor from '@/components/MyEditor.vue'
import Page from '@/components/Page.vue'

const roleRef = reactive(new roleClass())
const menuTreeRef = reactive(new menuTreeClass())
const addRoleRef = ref<FormInstance>()
const roleMenu = reactive(new roleMenuClass())
const treeRef = ref<InstanceType<typeof ElTree>>()
const searchRole = () => {
  pageRole(roleRef.rolePage).then(res => {
    const role = res.data.records as roleInfo[]
    roleRef.roleTable = role
    roleRef.rolePage.page = res.data.current
    roleRef.rolePage.size = res.data.size
    roleRef.rolePage.total = res.data.total
  })
}
const handleSizeChange = (val: number) => {
  roleRef.rolePage.size = val
  searchRole()
}
const handleCurrentChange = (val: number) => {
  roleRef.rolePage.page = val
  searchRole()
}
onMounted(() => {
  searchRole()
})
const edit = (row: roleInfo) => {
  getRoleDetail(row.id).then(role => {
    const data = role.data as roleInfo
    roleRef.roleAdd = data
    roleRef.dialogFormVisible = true
  })
}
const chengStatus = (row: roleInfo) => {
  const datas = new roleClass().roleData
  datas.id = row.id
  datas.work = row.work
  updateRole(datas).then(() => {
    ElMessage({
      message: '更改状态成',
      type: 'success'
    })
    searchRole()
  })
}
const deleted = (row: roleInfo) => {
  deleteRole(row.id).then(() => {
    ElMessage({
      message: '删除角色成功',
      type: 'success'
    })
    searchRole()
  })
}
const saveRole = (addRoleF: FormInstance | undefined) => {
  if (!addRoleF) return
  addRoleF.validate((validate: boolean) => {
    if (validate) {
      if (roleRef.roleAdd.id && roleRef.roleAdd.id != null) {
        updateRole(roleRef.roleAdd).then(() => {
          ElMessage({
            message: '更新角色成功',
            type: 'success'
          })
          roleRef.dialogFormVisible = false
          searchRole()
        })
      } else {
        addRole(roleRef.roleAdd).then(() => {
          ElMessage({
            message: '添加角色成功',
            type: 'success'
          })
          roleRef.dialogFormVisible = false
          searchRole()
        })
      }
    }
  })
}
const resetForm = (addRoleRef: FormInstance | undefined) => {
  if (!addRoleRef) return
  addRoleRef.resetFields()
}
const addMenu = (row: roleInfo) => {
  roleRef.roleId = row.id
  roleRef.dialogMenu = true
  treeSelect('', '', roleRef.roleId).then(res => {
    treeRef.value!.setCheckedKeys([], false)
    const data = res.data as menuTreeInfo[]
    menuTreeRef.treeData = data
    const ids = [] as number[]
    getAllCheck(data, ids)
    treeRef.value!.setCheckedKeys(ids, true)
  })
}
const getAllCheck = (data: menuTreeInfo[], ids: number[]) => {
  if (data) {
    data.forEach(st => {
      if (st.id !== null && st.checked === true) {
        ids.push(st.id)
      }
      if (st.children) {
        getAllCheck(st.children, ids)
      } else {
        return
      }
    })
  }
  return ids
}

const handleNodeClick = (data: baseTreeInfo[]) => {
  console.log(data)
}
const saveTree = () => {
  const data = treeRef.value!.getCheckedNodes(false, false) as menuTreeInfo[]
  roleMenu.roleMenuData.roleId = roleRef.roleId
  roleMenu.roleMenuData.menuId = data.map(s => s.id)
  roleMenu.roleMenuData.menuId.concat(data.map(s => s.pid))
  saveRoleMenu(roleMenu.roleMenuData).then(() => {
    ElMessage({
      message: '保存权限成功',
      type: 'success'
    })
    roleRef.dialogMenu = false
  })
}
const isTreeChecked = (treeCheck: boolean) => {
  roleRef.treeChecked = !treeCheck
  if (menuTreeRef.treeData) {
    const ids = [] as number[]
    getAllRoleId(menuTreeRef.treeData, ids)
    treeRef.value!.setCheckedKeys([], false)

    if (roleRef.treeChecked) {
      treeRef.value!.setCheckedKeys(ids, false)
    } else {
      treeRef.value!.setCheckedKeys([], false)
    }
  }
}
const getAllRoleId = (data: menuTreeInfo[], ids: number[]) => {
  if (data) {
    data.forEach(st => {
      if (st.id !== null) {
        ids.push(st.id)
      }
      if (st.children) {
        getAllRoleId(st.children, ids)
      } else {
        return
      }
    })
  }
  return ids
}
</script>
<style lang="scss" scoped>
.pagination-block {
  position: relative;

  .el-pagination {
    margin-top: 20px;
    position: absolute;
    right: 0%;
  }
}
.el-select {
  width: 200px;
}
</style>
